package org.datamining.guha.data.provider;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.datamining.guha.model.literal.Literal;

public class FileDataProvider extends AbstractDataProvider implements DataProvider {

	private FileReader fr;
	private String[] lines;
	private int currentLine = 0;
	
	/**
	 * Very simple implementation of {@link DataProvider}.
	 * <p>
	 * Literals on one row are delimited by double-colon.
	 * If literal is integer 1 then it is interpreted as a True, otherwise false.
	 * Lines starting with "#" are ignored.
	 * 
	 * @param rowLength
	 * @param filePath
	 * @throws IOException
	 */
    public FileDataProvider(int rowLength, File file) throws IOException {
    	// TODO implement far better FileDataProvider.
    	super(rowLength);
    	
    	String fileContent = null;
    	fr = new FileReader(file);
    	fileContent = IOUtils.toString(fr);
    	
    	String[] tempLines = fileContent.split("\n");
    	int lineCnt = 0;
    	for (String line : tempLines) {
			if (!(line.trim().startsWith("#") && line.trim().length() > 0)) {
				lineCnt++;
			}
		}
    	
    	lines = new String[lineCnt];
    	
    	lineCnt = 0;
    	for (String line : tempLines) {
    		if (! (line.trim().startsWith("#") && line.trim().length() > 0)) {
    			lines[lineCnt] = line.trim();
				lineCnt++;
			}
		}
    }
    
    /** @return true until the end of the file is reached. */
    public boolean isDataAvailable() {
    	return !((currentLine+1) > lines.length);
    }
    
	public List<Literal> nextData() {
		List<Literal> list = new ArrayList<Literal>(rowLength);
		
		if (!isDataAvailable()) {
			throw new RuntimeException("No data available!");
		}
		
		//get line
		String line = lines[currentLine];
		currentLine++;
		
		String[] items = line.split(":");
		for (int l = 0; l < rowLength; l++) {
			int it = Integer.parseInt(items[l]);
			if (it == 1) {
				list.add(positiveLiterals.get(l));
			} else {
				list.add(negativeLiterals.get(l));
			}
		}
		return list;
	}
}